package biz.datalk.industrialland.common.validated.validator;

import biz.datalk.industrialland.common.validated.DBField;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 数据库字段命名规则
 * @author tarofang@163.com
 * @date 2019-12-17
 */
public class DBFieldValidator implements ConstraintValidator<DBField, String> {
    @Override
    public void initialize(DBField constraintAnnotation) {
        // System.out.println("xxxxxxx" + constraintAnnotation);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.length() == 0) {
            return false;
        }

        boolean matches = value.matches("^[a-zA-Z$_][a-zA-Z0-9_]*$");
        if (!matches) {
            return false;
        }

        String split = "_";
        if (!value.contains(split)) {
            return true;
        }

        String[] arr = StringUtils.splitByWholeSeparatorPreserveAllTokens(value, split);

        boolean startWithNum = false;
        for (int index = 1, len = arr.length; index < len; index++) {
            if (arr[index].matches("^\\d.*$")) {
                startWithNum = true;
                break;
            }
        }

        return !startWithNum;
    }
}
